<template>
    <div class="qiehuan_content">
        <div class="InCardName_Box">
            <div class="InCardName"
                style=" border:0; position: sticky; top: 0; left: 0; width:100px; background: #13037d;"></div>
            <div class="InCardName" v-for="(item, i) of InName" @dblclick="handleInRename(i, 'in', item ? item : i)"
                :key="'InName' + i" :class="item?.length > 4 ? 'Name1' : ''" :title="item ? item : i">
                {{ item ? (item.length > 7 ? item.substring(0, 7) + '...' : item) : i }}
            </div>
        </div>
        <div class="aside">
            <div class="outCardName_content">
                <div class="outCardName_box">
                    <div class="outCardName btn_All">
                        ALL
                    </div>
                </div>

                <div class="outCardName_box" v-for="(item, i) of OutName" :key="'outName' + i">
                    <div class="outCardName" @dblclick="handleInRename(i, 'out', item ? item : i)"
                        :class="item?.length > 4 ? 'Name1' : ''" :title="item ? item : i">
                        {{ item ? (item.length > 7 ? item.substring(0, 7) + '...' : item) : i }}
                    </div>
                </div>
            </div>

            <div class="item">
                <div class="item_all" v-for="(item_i, i) in list" :class="[set_item_all_light(i) ? 'all_activing' : '']"
                    :key="'all' + i" @click="handleAllBtn(i)" :title="`输入通道${i + 1} => 所有输出通道`">
                    {{ i + 1 }} => all
                </div>

                <div class="item_i" v-for="(item_i, i) in list" :key="item_i + i">
                    <div class="item_j" v-for="(item_j, j) in item_i" :key="item_j + j"
                        :title="`输入通道${item_i[j].IN} => 输出通道${item_i[j].OUT}`" :class="[
                        OutCard.includes(item_i[j].OUT_CH) &&
                            InCard.includes(item_i[j].IN_CH)
                            ? 'wait_active'
                            : '',
                        SelectArray.includes(item_i[j].sceneIndex) ? 'active' : '',
                        item_i[j].disabled ? 'disabled' : '',]" @click="handleClickButton(item_i[j])">
                        {{ item_i[j].IN }} => {{ item_i[j].OUT }}
                    </div>
                </div>
            </div>
        </div>


    </div>
</template>

<script>
// import { readSync } from "fs";
// import _ from 'lodash'

import {
    LMX_getCardDataApi,
    LMX_getSwitchDataApi,
    LMX_sendDataApi,
} from "../api/qiehuan";
export default {
    name: "qiehuan",
    data() {
        return {
            SelectArray: [], // 已经选择
            list: [], // 二维数组
            OutCard: [], // 输出卡数组
            InCard: [], // 输入卡数组
            row_column_length: null, // 行或列的数量
            InName: {}, // 输入卡名称列表
            OutName: {}, // 输出卡名称列表
            timer: null, // 定时器；
        };
    },
    mounted() {
        // 获取初始化数据
        this.getList();

        this.timer = setInterval(() => {
            this.getSwitchData();
            console.log(this.SelectArray);
        }, 1000);

    },
    beforeDestroy() {
        clearInterval(this.timer);
    },
    methods: {
        // 判断全选按钮是否亮起
        set_item_all_light(i) {
            return this.InCard.includes(Math.ceil((i + 1) / 4))
        },

        // 处理全选按钮
        handleAllBtn(i) {
            if (this.set_item_all_light(i)) {
                LMX_sendDataApi({
                    in_to_all: {
                        in: `${i + 1}`,
                        out: "All"
                    },
                }).then(() => {

                }, err => {
                    console.log(err)
                    this.$message.error("切换失败！")
                })
            }
        },

        getList() {
            const self = this;
            const loading = this.$loading({
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)",
            });

            LMX_getCardDataApi({ tag: "ptn" })
                .then((res) => {
                    self.row_column_length = res.Type;
                    self.InName = res.InName;
                    self.OutName = res.OutName;
                    self.InCard = res.InCard;
                    self.OutCard = res.OutCard;
                })
                .then(() => {
                    // 设置按钮长度
                    let len = 100;
                    if (self.row_column_length > 96) {
                        len = 125;
                    }
                    document.getElementsByTagName('body')[0].style.setProperty("--len", `${len}px`);

                    loading.close();
                    self.computedGrid(self.row_column_length, self.row_column_length);
                })
                .catch((err) => {
                    console.log(err, "err");
                });
        },

        handleInRename(i, type, name) {
            const self = this;
            this.$prompt("请输入通道名字", "重新命名通道", {
                inputValue: name,
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                // 取消遮罩层关闭
                closeOnClickModal: false,
            })
                .then(({ value }) => {
                    let data;
                    if (type === "in") {
                        data = {
                            inRenameCh: {
                                ch: `${i}`, // 通道ID
                                rename: value, // 通道名
                            },
                        };
                    } else {
                        data = {
                            outRenameCh: {
                                ch: `${i}`, // 通道ID
                                rename: value, // 通道名
                            },
                        };
                    }
                    LMX_sendDataApi(data).then(() => {
                        this.$message.success("修改成功");
                        if (type === "in") {
                            self.InName[i] = value;
                        } else {
                            self.OutName[i] = value;
                        }
                        // clearInterval(this.timer)
                        // window.location.reload()
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "取消输入",
                    });
                });
        },

        handleClickButton(item) {
            if (
                !(
                    this.OutCard.includes(item.OUT_CH) && this.InCard.includes(item.IN_CH)
                )
            ) {
                return false;
            }
            if (this.SelectArray.includes(item.sceneIndex)) {
                // this.SelectArray.splice(this.SelectArray.indexOf(item.sceneIndex), 1)
                console.log(item.OUT, "关闭OUT");
                LMX_sendDataApi({
                    close_Channel: {
                        out: `${item.OUT}`,
                    },
                });

            } else {
                // let OUT=parseInt(item.OUT)
                // let IN=parseInt(item.IN)
                // for (let i in this.list){
                //     for (let j in this.list[i]){
                //         if (this.list[i][j].OUT===OUT&&this.list[i][j].IN!==IN){
                //             this.list[i][j].disabled=true
                //         }
                //     }
                // }
                // this.SelectArray.push(item.sceneIndex)
                console.log(item.OUT, "打开OUT");
                LMX_sendDataApi({
                    switch_in_out: {
                        in: `${item.IN}`,
                        out: `${item.OUT}`,
                    },
                });
            }
        },


        getSwitchData() {
            LMX_getSwitchDataApi({
                tag: "ptn",
            }).then((res) => {
                let SwitchStatus = res.SwitchStatus;
                let arrayOfSelectBack = [];
                for (let i in this.list) {
                    for (let j in this.list[i]) {
                        if (
                            this.OutCard.includes(this.list[i][j].OUT_CH) &&
                            this.InCard.includes(this.list[i][j].IN_CH) &&
                            SwitchStatus.includes(this.list[i][j].sceneIndex)
                        ) {
                            arrayOfSelectBack.push(this.list[i][j].sceneIndex);
                        }
                    }
                }
                this.SelectArray = [...arrayOfSelectBack];
            });
        },
        computedGrid(rows, columns) {
            if (rows % 4 !== 0) {
                return false;
            }
            if (columns % 4 !== 0) {
                return false;
            }
            let a = [];
            let b = [];
            for (let i = 1; i < rows * columns + 1; i++) {
                a.push({
                    sceneIndex: i,
                    IN: "",
                    OUT: "",
                    disabled: false,
                    OUT_CH: null,
                    IN_CH: null,
                });
            }
            for (let i = 0; i < a.length; i += columns) {
                b.push(a.slice(i, i + columns));
            }
            for (let i = 0; i < b.length; i++) {
                for (let j = 0; j < b[i].length; j++) {
                    b[i][j]["IN"] = j + 1;
                    b[i][j]["OUT"] = i + 1;
                }
            }
            let c = [...b].flat();
            // let outch = 1;
            let sun = columns * 4;
            let k = [];
            for (let i = 0; i < c.length; i += sun) {
                k.push(c.slice(i, i + sun));
            }
            for (let i = 0; i < k.length; i++) {
                for (let j = 0; j < k[i].length; j++) {
                    k[i][j].OUT_CH = i + 1;
                }
            }
            c = [...k].flat();
            let d = [];
            for (let i = 0; i < c.length; i += 4) {
                d.push(c.slice(i, i + 4));
            }
            for (let i = 0; i < d.length; i++) {
                for (let j = 0; j < d[i].length; j++) {
                    d[i][j]["IN_CH"] = i + 1;
                }
            }
            let e = d.flat();
            let g = [];
            for (let i = 0; i < e.length; i++) {
                if (e[i].OUT === 1) {
                    g.push(e[i]);
                }
            }
            for (let i = 0; i < g.length; i++) {
                for (let j = 0; j < e.length; j++) {
                    if (g[i].IN === e[j].IN) {
                        e[j].IN_CH = g[i].IN_CH;
                    }
                }
            }
            let f = [];
            for (let i = 0; i < e.length; i += columns) {
                f.push(e.slice(i, i + columns));
            }
            this.list = [...f];
        },
    },
};
</script>

<style scoped lang="scss">
// 按钮高度及其行高
$btn_height: 38px;

// 按钮主要色调
.disabled {
    background: linear-gradient(0deg, #696969, #a7a7a7);

}

.wait_active,
.all_activing {
    background: linear-gradient(0deg, #0308d3, #75b3ff) !important;
    cursor: pointer !important;
}

.all_activing:active {
    background: linear-gradient(0deg, #80bb09, #aed54d) !important;
}


.active {
    background: linear-gradient(0deg, #80bb09, #aed54d) !important;
    cursor: pointer !important;
}



.btn {
    box-sizing: border-box;
    width: var(--len);
    height: $btn_height;
    line-height: $btn_height;
    font-size: 16px;
    text-align: center;
    margin: 10px 5px;
}

.Name1 {
    font-size: 12px !important;
}

.qiehuan_content {
    box-sizing: border-box;
    overflow-x: auto;


    .InCardName_Box {
        position: sticky;
        top: 0;
        left: 0;
        display: inline-flex;
        white-space: nowrap;
        color: #fff;
        background: #13037d;

        .InCardName {
            display: inline-block;
            @extend .btn;
            background: #13037d;
            margin-top: 0 !important;
            margin-bottom: 0 !important;
        }
    }

    .aside {
        display: inline-flex;
        flex-direction: row;

        .outCardName_content {
            position: sticky;
            top: 0;
            left: 0;
            color: #fff;

            .outCardName_box {

                .outCardName {
                    @extend .btn;
                    width: 100px;
                    background: #13037d;
                    margin-left: 0;
                }

                .btn_All {
                    cursor: not-allowed;
                }
            }
        }

        .item {

            .item_all {
                display: inline-block;
                @extend .btn;
                @extend .disabled;
                margin-bottom: 0;
            }

            .item_i {
                display: flex;
                flex-direction: row;

                .item_j {
                    @extend .btn;
                    @extend .disabled;
                    margin-bottom: 0;
                }
            }
        }
    }
}
</style>
